<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>21点游戏</title>
    <!-- 引入高级AI策略 -->
    <script src="/js/strategy.js"></script>
    <!-- 游戏样式定义 -->
    <style>
        /* 全局样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 渐变背景 */
            margin: 0;
            padding: 20px;
            min-height: 100vh; /* 最小高度为视口高度 */
        }
        
        /* 游戏主容器 */
        .game-container {
            max-width: 1000px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95); /* 半透明白色背景 */
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1); /* 阴影效果 */
            backdrop-filter: blur(10px); /* 背景模糊效果 */
        }
        
        /* 难度选择器样式 */
        .difficulty-selector {
            text-align: center;
            margin-bottom: 30px;
            padding: 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); /* 渐变背景 */
            border-radius: 15px;
        }
        
        .difficulty-selector h3 {
            margin: 0 0 15px 0;
            color: #2c3e50;
            font-size: 1.3em;
        }
        
        #difficulty {
            padding: 10px 20px;
            border: 2px solid #3498db;
            border-radius: 25px;
            font-size: 16px;
            background: white;
            color: #2c3e50;
            outline: none;
        }
        
        /* 玩家和AI面板基础样式 */
        .board {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            padding: 20px;
            border-radius: 15px;
            transition: all 0.3s ease; /* 平滑过渡效果 */
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border: 2px solid #dee2e6;
        }
        
        /* 当前回合激活状态样式 */
        .active-turn {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); /* 绿色渐变背景 */
            border-color: #28a745; /* 绿色边框 */
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.2); /* 绿色阴影 */
        }
        
        .ai-board {
            margin-bottom: 40px;
        }
        
        .player-board, .ai-board {
            min-height: 180px;
        }
        
        /* 卡牌容器样式 */
        .cards-container {
            display: flex;
            gap: 15px; /* 卡牌间距 */
            margin-top: 15px;
            flex-wrap: wrap; /* 允许换行 */
        }
        
        /* 卡牌基础样式 */
        .card {
            width: 70px;
            height: 100px;
            border-radius: 8px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 28px;
            font-weight: bold;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); /* 卡牌阴影 */
            transition: all 0.3s ease; /* 平滑过渡 */
            position: relative;
            overflow: hidden;
        }

        /* 初始卡牌（背面）样式 */
        .initial-card {
            position: relative;
            overflow: hidden;
        }

        

        /* 结算动画关键帧 */
        @keyframes settleCard {
            0% {
                transform: scale(1);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            }
            50% {
                transform: scale(1.15); /* 放大效果 */
                box-shadow: 0 8px 16px rgba(0, 0, 0, 0.4);
            }
            100% {
                transform: scale(1);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            }
        }

        /* 揭示动画关键帧（翻转效果） */
        @keyframes revealCard {
            0% {
                transform: rotateY(0deg); /* 起始角度 */
                background: linear-gradient(135deg, #1a237e, #283593); /* 背面颜色 */
            }
            50% {
                transform: rotateY(90deg); /* 中间角度 */
                background: linear-gradient(135deg, #1a237e, #283593); /* 保持背面颜色 */
            }
            100% {
                transform: rotateY(0deg); /* 回到正面 */
                background: linear-gradient(135deg, #ffffff, #f5f5f5); /* 正面颜色 */
            }
        }

        /* 卡牌背面设计 - 简洁扑克牌风格 */
        .initial-card {
            background: linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 50%, #bdbdbd 100%); /* 灰白色渐变背景 */
            border: 2px solid #ccc;
            position: relative;
            overflow: hidden;
        }
        

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 500px;
            text-align: center;
            animation: modalFadeIn 0.5s ease-out;
        }

        @keyframes modalFadeIn {
            0% {
                transform: scale(0.8);
                opacity: 0;
            }
            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        .board.settle-highlight {
            animation: boardHighlight 1s ease-in-out;
        }

        @keyframes boardHighlight {
            0% {
                background-color: rgba(144, 238, 144, 0.3);
            }
            50% {
                background-color: rgba(144, 238, 144, 0.8);
            }
            100% {
                background-color: rgba(144, 238, 144, 0.3);
            }
        }
        
        .initial-card {
            background-color: #1a73e8;
            color: white;
        }
        
        .visible-card {
            background-color: white;
            border: 1px solid #ccc;
            color: black;
        }
        
        .center-area {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            padding: 20px;
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border-radius: 15px;
            border: 2px solid #90caf9;
        }
        
        .stats {
            flex: 1;
            text-align: center;
            padding: 15px;
        }
        
        .stats h3 {
            margin: 0 0 10px 0;
            color: #1565c0;
            font-size: 1.2em;
        }
        
        .stats div {
            font-size: 1.1em;
            color: #2c3e50;
            font-weight: 500;
        }
        
        .deck-area {
            flex: 1;
            text-align: center;
            padding: 15px;
        }
        
        .deck-area h3 {
            margin: 0 0 10px 0;
            color: #1565c0;
            font-size: 1.2em;
        }
        
        .deck-area div {
            font-size: 1.1em;
            color: #2c3e50;
            font-weight: 500;
        }
        
        .buttons {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
        }
        
        button {
            padding: 15px 30px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
        }
        
        button:active {
            transform: translateY(0);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        }
        
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        #draw-button {
            background: linear-gradient(135deg, #4caf50 0%, #45a049 100%);
            color: white;
        }
        
        #skip-button {
            background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
            color: white;
        }
        
        #settle-button {
            background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%);
            color: white;
        }
        
        #start-button {
            background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
            color: white;
            padding: 18px 40px;
            font-size: 18px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 500px;
            text-align: center;
        }
        
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1 style="text-align: center;">21点游戏</h1>
        
        <div class="difficulty-selector" id="difficulty-selector">
            <h3>选择AI难度：</h3>
            <select id="difficulty">
                <option value="easy">简单</option>
                <option value="normal">普通</option>
                <option value="hard">困难</option>
                <option value="nightmare">噩梦</option>
            </select>
            <br><br>
            <button id="start-button">开始游戏</button>
        </div>
        
        <div class="board ai-board" id="ai-board">
            <div class="stats">
                <h3>AI</h3>
                <div id="ai-stats">牌数: 0 | 点数: ?/21</div>
                <div id="ai-settle-indicator"></div>
            </div>
            <div class="cards-container" id="ai-cards">
                <!-- AI的牌将在这里显示 -->
            </div>
        </div>
        
        <div class="center-area">
            <div class="stats">
                <h3>玩家统计</h3>
                <div id="player-stats">牌数: 0 | 点数: 0/21</div>
            </div>
            
            <div class="deck-area">
                <h3>牌组</h3>
                <div id="deck-count">剩余: 52</div>
            </div>
            
            <div class="stats">
                <h3>AI统计</h3>
                <div id="ai-visible-stats">可见牌: 0 | 点数: 0/21</div>
            </div>
        </div>
        
        <div class="board player-board" id="player-board">
            <div class="stats">
                <h3>玩家</h3>
                <div id="player-settle-indicator"></div>
            </div>
            <div class="cards-container" id="player-cards">
                <!-- 玩家的牌将在这里显示 -->
            </div>
        </div>
        
        <div class="buttons">
            <button id="draw-button" disabled>抽牌</button>
            <button id="skip-button" disabled>结束</button>
            <button id="settle-button" disabled>结算</button>
        </div>
    </div>
    
    <div class="modal" id="result-modal">
        <div class="modal-content">
            <h2>游戏结果</h2>
            <div id="result-content"></div>
            <button id="play-again-button">再玩一次</button>
        </div>
    </div>

    <script>
        // ========== 游戏状态变量 ==========
        let deck = []; // 牌组数组
        let playerCards = []; // 玩家抽的牌
        let aiCards = []; // AI抽的牌
        let playerInitialCard = 0; // 玩家的初始牌点数
        let aiInitialCard = 0; // AI的初始牌点数
        let playerSettled = false; // 玩家是否已结算
        let aiSettled = false; // AI是否已结算
        let currentTurn = 'player'; // 当前回合（player或ai）
        let gameStarted = false; // 游戏是否已开始
        let aiDifficulty = 'normal'; // AI难度级别
        
        // ========== DOM元素引用 ==========
        const playerBoard = document.getElementById('player-board'); // 玩家面板
        const aiBoard = document.getElementById('ai-board'); // AI面板
        const playerCardsContainer = document.getElementById('player-cards'); // 玩家卡牌容器
        const aiCardsContainer = document.getElementById('ai-cards'); // AI卡牌容器
        const playerStats = document.getElementById('player-stats'); // 玩家统计信息
        const aiStats = document.getElementById('ai-stats'); // AI统计信息
        const aiVisibleStats = document.getElementById('ai-visible-stats'); // AI可见牌统计
        const deckCount = document.getElementById('deck-count'); // 牌组剩余数量显示
        const drawButton = document.getElementById('draw-button'); // 抽牌按钮
        const skipButton = document.getElementById('skip-button'); // 结束回合按钮
        const settleButton = document.getElementById('settle-button'); // 结算按钮
        const startButton = document.getElementById('start-button'); // 开始游戏按钮
        const difficultySelector = document.getElementById('difficulty-selector'); // 难度选择器容器
        const difficultySelect = document.getElementById('difficulty'); // 难度选择下拉框
        const resultModal = document.getElementById('result-modal'); // 结果模态框
        const resultContent = document.getElementById('result-content'); // 结果内容区域
        const playAgainButton = document.getElementById('play-again-button'); // 再玩一次按钮
        const playerSettleIndicator = document.getElementById('player-settle-indicator'); // 玩家结算指示器
        const aiSettleIndicator = document.getElementById('ai-settle-indicator'); // AI结算指示器
        
        // ========== 初始化游戏 ==========
        function initGame() {
            // 创建牌组 (1-13各4张，共52张牌)
            deck = [];
            for (let i = 1; i <= 13; i++) {
                for (let j = 0; j < 4; j++) {
                    deck.push(i); // 每种点数4张牌
                }
            }
            
            // 洗牌
            shuffleDeck();
            
            // 重置游戏状态
            playerCards = [];
            aiCards = [];
            playerSettled = false;
            aiSettled = false;
            currentTurn = 'player'; // 玩家先手
            gameStarted = true;
            aiDifficulty = difficultySelect.value; // 获取选择的AI难度
            
            // 重置策略状态
            if (typeof resetStrategyState === 'function') {
                resetStrategyState();
            }
            
            // 清空牌容器
            playerCardsContainer.innerHTML = '';
            aiCardsContainer.innerHTML = '';
            
            // 禁用开始按钮和难度选择
            startButton.disabled = true;
            difficultySelect.disabled = true;
            
            // 启用玩家按钮
            drawButton.disabled = false;
            skipButton.disabled = false;
            settleButton.disabled = false;
            
            // 隐藏难度选择区域
            difficultySelector.classList.add('hidden');
            
            // 分发初始牌（每人一张初始牌）
            playerInitialCard = drawCard();
            aiInitialCard = drawCard();
            
            // 显示玩家的初始牌（背面）
            const playerInitialCardElement = document.createElement('div');
            playerInitialCardElement.className = 'card initial-card';
            playerInitialCardElement.textContent = '?'; // 显示问号表示背面
            playerCardsContainer.appendChild(playerInitialCardElement);
            
            // 显示AI的初始牌（背面）
            const aiInitialCardElement = document.createElement('div');
            aiInitialCardElement.className = 'card initial-card';
            aiInitialCardElement.textContent = '?'; // 显示问号表示背面
            aiCardsContainer.appendChild(aiInitialCardElement);
            
            // 更新统计信息
            updateStats();
            
            // 设置玩家回合（高亮显示）
            playerBoard.classList.add('active-turn');
        }
        
        // ========== 洗牌函数 ==========
        function shuffleDeck() {
            // Fisher-Yates 洗牌算法
            for (let i = deck.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1)); // 随机选择索引
                [deck[i], deck[j]] = [deck[j], deck[i]]; // 交换元素位置
            }
        }
        
        // ========== 从牌组抽一张牌 ==========
        function drawCard() {
            if (deck.length === 0) {
                alert('牌组已空！'); // 牌组为空时提示
                return 0; // 返回0点
            }
            return deck.pop(); // 从牌组末尾移除并返回一张牌
        }
        
        // ========== 玩家抽牌 ==========
        function playerDrawCard() {
            if (currentTurn !== 'player' || playerSettled) return; // 非玩家回合或已结算时返回
            
            const card = drawCard(); // 从牌组抽一张牌
            playerCards.push(card); // 添加到玩家手牌
            
            // 记录玩家抽牌行动
            if (typeof recordPlayerAction === 'function') {
                recordPlayerAction('hit', calcPlayerScore());
            }
            
            // 创建卡牌DOM元素
            const cardElement = document.createElement('div');
            cardElement.className = 'card visible-card'; // 可见卡牌样式
            cardElement.textContent = card; // 显示卡牌点数
            playerCardsContainer.appendChild(cardElement);
            
            // 添加抽牌动画效果
            cardElement.classList.add('draw-animation');
            
            updateStats(); // 更新统计信息
            
            // 检查是否爆牌（超过21点）
            if (calcPlayerScore() > 21) {
                setTimeout(endGame, 600); // 延迟600ms后结束游戏
                return;
            }
            
            // 抽牌后自动结束当前回合（延迟300ms）
            setTimeout(playerSkip, 300);
        }
        
        // ========== AI抽牌 ==========
        function aiDrawCard() {
            const card = drawCard(); // 从牌组抽一张牌
            aiCards.push(card); // 添加到AI手牌
            
            // 创建卡牌DOM元素
            const cardElement = document.createElement('div');
            cardElement.className = 'card visible-card'; // 可见卡牌样式
            cardElement.textContent = card; // 显示卡牌点数
            aiCardsContainer.appendChild(cardElement);
            
            // 添加抽牌动画效果
            cardElement.classList.add('draw-animation');
            
            updateStats(); // 更新统计信息
            
            // 检查AI是否爆牌（超过21点）
            if (calcAIScore() > 21) {
                setTimeout(endGame, 600); // 延迟600ms后结束游戏
                return true; // 返回true表示爆牌
            }
            return false; // 返回false表示未爆牌
        }
        
        // ========== 计算玩家点数 ==========
        function calcPlayerScore() {
            return playerInitialCard + playerCards.reduce((sum, card) => sum + card, 0); // 初始牌 + 抽的牌总和
        }
        
        // ========== 计算AI点数 ==========
        function calcAIScore() {
            return aiInitialCard + aiCards.reduce((sum, card) => sum + card, 0); // 初始牌 + 抽的牌总和
        }
        
        // ========== 计算AI可见点数 ==========
        function calcAIVisibleScore() {
            return aiCards.reduce((sum, card) => sum + card, 0); // 只计算抽的牌（初始牌不可见）
        }
        
        // ========== 更新统计信息 ==========
        function updateStats() {
            // 更新玩家统计：初始牌1张 + 抽的牌数量，总点数
            playerStats.textContent = `牌数: ${1 + playerCards.length} | 点数: ${calcPlayerScore()}/21`;
            
            // 更新AI统计：初始牌1张 + 抽的牌数量，总点数显示为?（初始牌不可见）
            aiStats.textContent = `牌数: ${1 + aiCards.length} | 点数: ?/21`;
            
            // 更新AI可见统计：只显示抽的牌数量和点数
            aiVisibleStats.textContent = `可见牌: ${aiCards.length} | 点数: ${calcAIVisibleScore()}/21`;
            
            // 更新牌组剩余数量
            deckCount.textContent = `剩余: ${deck.length}`;
            
            // 更新玩家结算状态显示
            if (playerSettled) {
                playerSettleIndicator.textContent = '已结算';
            }
            
            // 更新AI结算状态显示
            if (aiSettled) {
                aiSettleIndicator.textContent = '已结算';
            }
        }
        
        // ========== 玩家跳过回合 ==========
        function playerSkip() {
            if (currentTurn !== 'player' || playerSettled) return; // 非玩家回合或已结算时返回
            
            // 切换到AI回合
            switchTurn();
        }
        
        // ========== 玩家结算 ==========
        function playerSettle() {
            if (playerSettled) return; // 已结算时返回
            
            playerSettled = true; // 标记玩家已结算
            playerSettleIndicator.textContent = '已结算'; // 更新结算指示器
            settleButton.disabled = true; // 禁用结算按钮
            
            // 记录玩家结算行动
            if (typeof recordPlayerAction === 'function') {
                recordPlayerAction('settle', calcPlayerScore());
            }
            
            // 添加结算高亮动画效果
            playerBoard.classList.add('settle-highlight');
            
            // 为玩家所有牌添加结算动画
            document.querySelectorAll('#player-cards .card').forEach(card => {
                card.classList.add('settle-animation');
            });
            
            // 如果AI也已结算，结束游戏
            if (aiSettled) {
                setTimeout(endGame, 600); // 延迟600ms后结束游戏
            } else {
                // 切换到AI回合
                setTimeout(switchTurn, 600); // 延迟600ms后切换回合
            }
        }
        
        // ========== 切换回合 ==========
        function switchTurn() {
            // 移除所有活动状态（取消高亮）
            playerBoard.classList.remove('active-turn');
            aiBoard.classList.remove('active-turn');
            
            // 如果双方都已结算，结束游戏
            if (playerSettled && aiSettled) {
                setTimeout(endGame, 600); // 延迟600ms后结束游戏
                return;
            }
            
            // 如果当前是玩家回合且AI未结算，切换到AI回合
            if (currentTurn === 'player' && !aiSettled) {
                currentTurn = 'ai'; // 设置为AI回合
                aiBoard.classList.add('active-turn'); // AI面板高亮
                
                // 禁用玩家按钮（AI回合时玩家不能操作）
                drawButton.disabled = true;
                skipButton.disabled = true;
                
                // 开始AI回合（延迟1000ms给玩家反应时间）
                setTimeout(startAITurn, 1000);
            } 
            // 如果当前是AI回合且玩家未结算，切换到玩家回合
            else if (currentTurn === 'ai' && !playerSettled) {
                currentTurn = 'player'; // 设置为玩家回合
                playerBoard.classList.add('active-turn'); // 玩家面板高亮
                
                // 启用玩家按钮（玩家回合时可以操作）
                drawButton.disabled = false;
                skipButton.disabled = false;
            }
            // 如果一方已结算，继续切换回合直到另一方也结算
            else {
                // 反转回合继续切换（处理一方已结算的情况）
                currentTurn = currentTurn === 'player' ? 'ai' : 'player';
                setTimeout(switchTurn, 600); // 延迟600ms后继续切换
            }
        }
        
        // ========== AI回合逻辑 ==========
        function startAITurn() {
            if (aiSettled) {
                switchTurn(); // AI已结算时直接切换回合
                return;
            }
            
            const aiScore = calcAIScore(); // 计算AI当前点数
            const playerVisibleScore = calcAIVisibleScore(); // 玩家可见点数
            
            let decision;
            
            // 根据不同难度使用不同的决策策略
            switch (aiDifficulty) {
                case 'easy':
                case 'normal':
                    // 简单和普通难度保持原有逻辑
                    const thresholds = {
                        easy: 16,
                        normal: 17
                    };
                    const settleChance = {
                        easy: 0.3,
                        normal: 0.5
                    };
                    
                    if (aiScore < thresholds[aiDifficulty]) {
                        decision = 'hit';
                    } else {
                        decision = Math.random() < settleChance[aiDifficulty] ? 'settle' : 'continue';
                    }
                    break;
                    
                case 'hard':
                    // 困难难度使用高级策略
                    decision = hardDifficultyStrategy(
                        aiScore, 
                        playerVisibleScore, 
                        aiCards, 
                        playerCards, 
                        deck.length
                    );
                    break;
                    
                case 'nightmare':
                    // 噩梦难度使用玩家行为分析策略
                    decision = nightmareDifficultyStrategy(
                        aiScore,
                        playerVisibleScore,
                        aiCards,
                        playerCards,
                        deck.length,
                        playerDecisions.map(d => d.action)
                    );
                    
                    // 保存分析日志
                    const gameData = {
                        aiScore,
                        playerVisibleScore,
                        deckSize: deck.length,
                        decision
                    };
                    const playerProfile = analyzePlayerBehavior(playerDecisions.map(d => d.action));
                    saveAnalysisLog(gameData, playerProfile, decision);
                    break;
            }
            
            // 执行决策
            if (decision === 'hit') {
                const busted = aiDrawCard(); // 抽牌并检查是否爆牌
                if (!busted) {
                    setTimeout(switchTurn, 1000); // 抽牌后自动结束回合
                }
            } else if (decision === 'settle') {
                aiSettled = true;
                aiSettleIndicator.textContent = '已结算';
                aiBoard.classList.add('settle-highlight');
                
                document.querySelectorAll('#ai-cards .card').forEach(card => {
                    card.classList.add('settle-animation');
                });
                
                if (playerSettled) {
                    setTimeout(endGame, 600);
                    return;
                }
                setTimeout(switchTurn, 600);
            } else {
                // continue - 直接结束回合
                setTimeout(switchTurn, 600);
            }
        }
        
        // ========== 结束游戏并显示结果 ==========
        function endGame() {
            // 显示初始牌并添加揭示动画（翻转效果）
            document.querySelectorAll('.initial-card').forEach(card => {
                card.textContent = card === playerCardsContainer.firstChild ? playerInitialCard : aiInitialCard; // 显示实际点数
                card.classList.add('reveal-animation'); // 添加揭示动画
            });
            
            // 为所有牌添加结算动画（放大缩小效果）
            document.querySelectorAll('.card').forEach(card => {
                card.classList.add('settle-animation');
            });
            
            // 为结算的玩家添加高亮动画
            if (playerSettled) {
                playerBoard.classList.add('settle-highlight');
            }
            if (aiSettled) {
                aiBoard.classList.add('settle-highlight');
            }
            
            // 延迟显示结果，等待动画完成（800ms后）
            setTimeout(() => {
                const playerScore = calcPlayerScore(); // 计算玩家总点数
                const aiScore = calcAIScore(); // 计算AI总点数
                
                // 构建结果文本（显示详细计算过程）
                let resultText = `
                    <p>玩家: ${playerInitialCard} + ${playerCards.join('+')} = ${playerScore}</p>
                    <p>AI: ${aiInitialCard} + ${aiCards.join('+')} = ${aiScore}</p>
                `;
                
                // 判断游戏结果
                if (playerScore > 21) {
                    resultText += '<p>玩家爆牌，AI胜利！</p>';
                } else if (aiScore > 21) {
                    resultText += '<p>AI爆牌，玩家胜利！</p>';
                } else if (playerSettled && aiSettled) {
                    // 双方都已结算，比较点数
                    if (playerScore > aiScore) {
                        resultText += '<p>玩家更接近21点，玩家胜利！</p>';
                    } else if (aiScore > playerScore) {
                        resultText += '<p>AI更接近21点，AI胜利！</p>';
                    } else {
                        resultText += '<p>平局！</p>';
                    }
                } else if (playerScore === 21) {
                    resultText += '<p>玩家达成21点，玩家胜利！</p>';
                } else if (aiScore === 21) {
                    resultText += '<p>AI达成21点，AI胜利！</p>';
                }
                
                // 显示结果模态框
                resultContent.innerHTML = resultText;
                resultModal.style.display = 'flex';
            }, 800);
        }
        
        // ========== 重置游戏 ==========
        function resetGame() {
            resultModal.style.display = 'none'; // 隐藏结果模态框
            playerBoard.classList.remove('active-turn'); // 移除玩家高亮
            aiBoard.classList.remove('active-turn'); // 移除AI高亮
            playerSettleIndicator.textContent = ''; // 清空玩家结算指示
            aiSettleIndicator.textContent = ''; // 清空AI结算指示
            
            // 显示难度选择区域
            difficultySelector.classList.remove('hidden');
            startButton.disabled = false; // 启用开始按钮
            difficultySelect.disabled = false; // 启用难度选择
            
            // 禁用游戏操作按钮
            drawButton.disabled = true;
            skipButton.disabled = true;
            settleButton.disabled = true;
            
            gameStarted = false; // 标记游戏未开始
        }
        
        // ========== 事件监听器 ==========
        startButton.addEventListener('click', initGame); // 开始游戏按钮点击事件
        drawButton.addEventListener('click', playerDrawCard); // 抽牌按钮点击事件
        skipButton.addEventListener('click', playerSkip); // 结束回合按钮点击事件
        settleButton.addEventListener('click', playerSettle); // 结算按钮点击事件
        playAgainButton.addEventListener('click', resetGame); // 再玩一次按钮点击事件
        
        // ========== 初始状态设置 ==========
        drawButton.disabled = true; // 初始禁用抽牌按钮
        skipButton.disabled = true; // 初始禁用结束回合按钮
        settleButton.disabled = true; // 初始禁用结算按钮
    </script>
</body>
</html>
